package com.ruoyi.system.service.impl;

import com.alibaba.fastjson.JSON;
import com.ruoyi.system.WeightTableBeanDto;
import com.ruoyi.system.domain.WeightTableBean;
import com.ruoyi.system.mapper.WeightMapper;
import com.ruoyi.system.service.WeightService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class WeightServiceImpl implements WeightService {

    @Autowired
    private WeightMapper weightMapper;

    @Override
    public WeightTableBean selectInfoById(Long configId) {
        WeightTableBean weightTableBean = weightMapper.selectInfoById(configId);
        return weightTableBean;
    }

    @Override
    public List<WeightTableBean> selectOneInfo(Integer userId) {

        if (userId == null) {
            throw new RuntimeException("用户ID不能为空！");
        }

        List<WeightTableBean> weightTableBeans = weightMapper.selectOneInfo(userId);
        return weightTableBeans;
    }

    @Override
    public Integer insertOneData(WeightTableBeanDto weightTableBeanDto) {
        List<WeightTableBean> weightList = weightTableBeanDto.getWeightList();
        log.info("接口集合的长度:{}", weightList.size());

        List<WeightTableBean> insertList = new ArrayList<>();
        //遍历一下集合，根据日期+体重，查询一下是否存在该笔数据，存在了后续不新增
        for (WeightTableBean weightTableBean : weightList) {
            WeightTableBean selectWeightBean = weightMapper.selectByBean(weightTableBean);
            if (selectWeightBean == null) {
                insertList.add(weightTableBean);
            }
        }
        log.info("开始插入数据:{}", JSON.toJSONString(insertList));

        if (CollectionUtils.isEmpty(insertList)) {
            throw new RuntimeException("已保存所有数据");
        }

        weightMapper.insertOneData(insertList);
        return insertList.size();
    }

}
